package com.teamin.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.cj.core.util.StringUtils;
import com.teamin.config.ErrorCode;
import com.teamin.entity.*;
import com.teamin.security.AESUtils;
import com.teamin.service.*;
import com.teamin.service.impl.*;
import com.teamin.service.labelService.LabelService;
import com.teamin.utils.Utils;
import com.teamin.web.entityJsonFilter.TaskJsonFilter;
import com.teamin.web.exception.GlobalErrorInfoException;
import com.teamin.web.model.ErrorInfo;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import uk.co.jemos.podam.api.PodamFactory;
import uk.co.jemos.podam.api.PodamFactoryImpl;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/v1")
@Api(description = "任务相关接口",tags = "任务")
public class TaskController extends BaseController {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private TaskServiceImpl taskService;

	@Autowired
	private FileServiceImpl fileService;

	@Autowired
	private MessageServiceImpl messageService;
	@Autowired
	private UserServiceImpl userService;
	@Autowired
	private CircleService circleService;

	@Autowired
	private WebsocketServiceImpl websocketService ;

	@Autowired
	private WxService wxService;

	@Autowired
	private WxGroupService wxGroupService;

	@Autowired
	private LogService logService;

	@Autowired
	private LabelService labelService;

	PodamFactory factory = new PodamFactoryImpl();

	/**
	 * 删除任务
	 *
	 * @param taskId
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "删除任务接口")
	@RequestMapping(value = "/tasks/{taskId}", method = RequestMethod.DELETE)
	public String deleteTask(@PathVariable("taskId") Long taskId,
							 HttpServletRequest request,
							 @RequestAttribute("loginUserId") Long loginUserId,
							 @RequestAttribute("userFlag") String userFlag) throws Exception {
		// 任务不属于用户
		if (!taskService.userHasTask(getLoginUserId(request), taskId)) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_DELETE_TASK));
		}

		CircleEntity cirUer = taskService.getCirclesByTask(taskId, loginUserId);;
		taskService.deleteTaskById(taskId,loginUserId,cirUer.getCircleId(),userFlag);
		return "success";
	}

	/**
	 * 查看一个任务
	 *
	 * @param taskId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/tasks/{taskId}", method = RequestMethod.GET)
	public TaskEntity getTask(@PathVariable("taskId") Long taskId, HttpServletRequest request) throws Exception {


		// 任务不属于用户
		TaskEntity taskEntity = taskService.selectTaskById(taskId);
		//JSONObject jsonObject = JSON.
		if (!taskService.userHasTask(getLoginUserId(request), taskId)) {
			//throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_VIEW_TASK));
			taskEntity.setReadOnly(true);
		}

		//任务已不存在
		if(taskEntity == null || taskEntity.getIsdelete() == 1) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.TASK_DELETED));
		}

		return taskEntity;
	}

	/**
	 * 查看一个任务
	 *
	 * @param taskId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/v010/tasks/{taskId}", method = RequestMethod.GET)
	public TaskEntity getTaskV010(@PathVariable("taskId") Long taskId,@RequestAttribute("loginUserId") Long loginUserId) throws Exception {


		CircleEntity cirUer = taskService.getCirclesByTask(taskId, loginUserId);
		// 任务不属于用户
		TaskEntity taskEntity = taskService.selectTaskV010AndCommentAndAttentionUser(taskId,loginUserId,cirUer.getCircleId());
		//JSONObject jsonObject = JSON.
		if (!taskService.userHasTask(loginUserId, taskId)) {
			//throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_VIEW_TASK));
			taskEntity.setReadOnly(true);
	}

		//任务已不存在
		if(taskEntity == null || taskEntity.getIsdelete() == 1) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.TASK_DELETED));
		}

		return taskEntity;
	}

	/**
	 * 查看一个任务的日志
	 *
	 * @param taskId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/tasks/{taskId}/log", method = RequestMethod.GET)
	public List<TaskLogEntity> getTaskLog(@PathVariable("taskId") Long taskId,@RequestAttribute("loginUserId") Long loginUserId) throws Exception {

		// 任务不属于用户
		if (!taskService.userHasTask(loginUserId, taskId)) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_VIEW_COMMENT));
		}
		return logService.selectTaskLog(taskId) ;
	}

	/**
	 * 更新任务
	 *
	 * @param taskEntity
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/tasks/{taskId}", method = RequestMethod.PUT)
	public Object updateTask(@PathVariable("taskId") Long taskId,@Valid @ModelAttribute TaskEntity taskEntity,@Valid @ModelAttribute TaskRemindEntity taskRemindEntity,
							 String planFinishTime,  @RequestAttribute("loginUserId") Long loginUserId,
							 @RequestAttribute("userFlag") String userFlag,BindingResult bindingResult) throws Exception {

		TaskEntity oldTask = taskService.selectTaskBase(taskId);

		//当指定的任务不在任务所在的圈子中
		if(taskEntity.getAssignerId() !=null && taskEntity.getAssignerId() != 0L && !taskService.userHasTask(taskEntity.getAssignerId(), taskId)) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FIND_USER_FROM_CIRCLE_NULL));
		}

		// 任务不属于用户
		if (!taskService.userHasTask(loginUserId, taskId)) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_UPDATE_TASK));
		}

		// 判断是否删除时间
		if (planFinishTime != null && planFinishTime.equals("")) {
			taskEntity.setIsShowTime(0);
			taskEntity.setIsDeleteTime(1);
		}

		Long controlUserId = loginUserId;

		// 防止没有设置时间时误传isshowtime = 1
		if (oldTask.getPlanFinishTime() == null && taskEntity.getPlanFinishTime() == null) {
			taskEntity.setIsShowTime(0);
		}

		taskService.updateTask(taskEntity, controlUserId,planFinishTime);

		TaskEntity newTask = taskService.selectTaskById(taskId);

		//更新任务结束时间或更新任务提醒
		if(taskRemindEntity != null && taskRemindEntity.getRemindMoveUpType()!= null && newTask.getPlanFinishTime() != null && taskRemindEntity.getRemindMoveUp() !=0) {
			taskService.updateTaskRemind(taskId, newTask.getPlanFinishTime(), taskRemindEntity, loginUserId);
			newTask.setTaskRemind(taskService.getTaskRemind(taskId,loginUserId));
		}else if((taskRemindEntity == null || StringUtils.isNullOrEmpty(taskRemindEntity.getRemindMoveUpType())) && !StringUtils.isNullOrEmpty(planFinishTime) && newTask.getTaskRemind() !=null) {//更新任务提醒
			taskService.updateTaskRemind(taskId, newTask.getPlanFinishTime(), newTask.getTaskRemind(), loginUserId);
		}else if ((planFinishTime != null && planFinishTime.equals("")) || (taskRemindEntity !=null && taskRemindEntity.getRemindMoveUp() != null && taskRemindEntity.getRemindMoveUp()==0) ) { //清空提醒
			taskService.deleteTaskRemind(taskId,loginUserId) ;
			newTask.setTaskRemind(null);
		}

		// 屏蔽关注者和评论字段
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.addMixIn(TaskEntity.class, TaskJsonFilter.class);
		String string = objectMapper.writeValueAsString(newTask);
		// 创建消息
		messageService.updateTaskMessage(oldTask, newTask, controlUserId,userFlag);
		//发送socket通知
		websocketService.sendCircle(loginUserId,taskService.getCirclesByTask(oldTask.getTaskId(),controlUserId).getCircleId(), WebsocketService.CirclePropertise.TASK, WebsocketService.Control.MODIFY,newTask,userFlag);
		//发送任务的同步
		websocketService.sendTask(loginUserId,taskService.getCirclesByTask(oldTask.getTaskId(),controlUserId).getCircleId(),taskId, WebsocketService.TaskPropertise.BASE, WebsocketService.Control.MODIFY,newTask,userFlag);
		return JSON.parseObject(string, Feature.OrderedField);
	}

	/**
	 * 查询一条任务的评论
	 *
	 * @param taskId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/tasks/{taskId}/comments", method = RequestMethod.GET)
	public List<CommentEntity> getComments(@PathVariable("taskId") Long taskId, @RequestAttribute("loginUserId") Long loginUserId)
			throws Exception {
		// 任务不属于用户
		if (!taskService.userHasTask(loginUserId, taskId)) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_VIEW_COMMENT));
		}
		return taskService.getComment(taskId);
	}

	/**
	 * 添加一条评论道任务
	 *
	 * @param commentEntity
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "任务新增一条评论")
	@RequestMapping(value = "/tasks/{taskId}/comments", method = RequestMethod.POST)
	@ApiResponse(code = 200,response = CommentEntity.class,message = "评论成功")
	public List<CommentEntity> addComments(@ModelAttribute CommentEntity commentEntity,
										   @ApiParam(value = "任务Id")@PathVariable("taskId") Long taskId, String uuid,
										   @ApiParam(value = "任务Id",hidden = true) @RequestAttribute("loginUserId") Long loginUserId,
										   @RequestAttribute("userFlag") String userFlag) throws Exception {
		// 任务不属于用户
		if (!taskService.userHasTask(loginUserId, taskId)) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_ADD_COMMENT));
		}

		CircleEntity circle = circleService.selectCircleByTask(taskId, loginUserId);
		// 用户发送的是图片
		if(commentEntity.getContentType() == CommentEntity.COMMENT_TYPE_IMG) {
			//获取临时文件大小
			FileTempEntity tempFile = fileService.selectTempFile(uuid);
			//临时文件跟当前任务的权限不匹配
			if(tempFile.getBelongType() != FileTempEntity.STORAGE_TYPE_TASK || !tempFile.getBelongId().equals(taskId )) {
				throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FILE_MATCH_ERROR));
			}else {
				Long fileSize = fileService.getFileSize(tempFile.getUuid());
				//上传的文件大小为0
				if(fileSize == 0 ) {
					throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FILE_MATCH_ERROR));
				}else {
					FileEntity file = new FileEntity() ;
					file.setUuid(tempFile.getUuid());
					file.setFileName(tempFile.getFileName());
					file.setSuffix(tempFile.getSuffix());
					file.setSize(fileSize);
					//新增文件
					fileService.insertFile(file) ;
					//设置评论的内容为图片
					commentEntity.setContent(""+file.getId());
					//删除临时文件
					fileService.deleteTempFile(tempFile.getUuid()) ;
				}
			}
		}else {//用户发送的评论是文本
			//是否有@用户
			List<Long> atUsers = Utils.getAtUserString(commentEntity.getContent());
			if(atUsers != null && atUsers.size() !=0 ) {
				if(atUsers.contains(0l)) {
					atUsers = null ;
				}
				//查找出@的用户
				List<NotifiEntity> sendMsgUser = circleService.selectNotifiMember(circle.getCircleId(), atUsers);
				CircleUserEntity curcleUser = circleService.selectMemberCircle(circle.getCircleId(), loginUserId);;
				messageService.addAtMessage(circle.getCircleId(),taskService.selectTaskBase(taskId),Utils.replaceAtString(commentEntity.getContent()),sendMsgUser,curcleUser,userFlag);
			}
		}

		commentEntity.setUserId(loginUserId);
		taskService.addComment(commentEntity);
		//发送任务的同步
		websocketService.sendTask(loginUserId,taskService.getCirclesByTask(taskId,loginUserId).getCircleId(),taskId, WebsocketService.TaskPropertise.COMMENT, WebsocketService.Control.ADD,commentEntity,userFlag);

		//圈子中任务的同步
		JSONObject json = new JSONObject();
		json.put("taskId",taskId) ;
		json.put("parentTaskId",taskService.getParentTaskId(taskId)) ;

		websocketService.sendCircle(loginUserId,circle.getCircleId(), WebsocketService.CirclePropertise.TASK_COMMENTS, WebsocketService.Control.ADD,json,userFlag);
		return taskService.getComment(taskId);
	}


	/**
	 * 更新用户查看任务评的位置
	 * @param taskId
	 * @return
	 */
	@RequestMapping(value = "/tasks/{taskId}/comments/action/readposition", method = RequestMethod.PUT)
	public void updateUserReadLastPosition( @PathVariable("taskId") Long taskId, @RequestAttribute("loginUserId") Long loginUserId,
											@RequestAttribute("userFlag") String userFlag) throws GlobalErrorInfoException {
		// 任务不属于用户
		if (!taskService.userHasTask(loginUserId, taskId)) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_ADD_COMMENT));
		}
		taskService.updateUserReadLastPosition(taskId,loginUserId,userFlag) ;
	}

	/**
	 * 一个任务下的全部成员
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/tasks/{taskId}/users", method = RequestMethod.GET)
	public List<UserEntity> getUsers(@PathVariable("taskId") Long taskId, HttpServletRequest request) throws Exception {
		// 任务不属于用户
		if (!taskService.userHasTask(getLoginUserId(request), taskId)) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_VIEW_TASK));
		}
		return taskService.getAttention(taskId);
	}

	/**
	 * 添加成员到task
	 *
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/tasks/{taskId}/users/{userId}", method = RequestMethod.POST)
	public List<UserEntity> addUser(@PathVariable("taskId") Long taskId, @PathVariable("userId") Long userId,
									@RequestAttribute("loginUserId") Long loginUserId) throws Exception {
		// 判断操作者是否对这个任务有操作权限
		if (!taskService.userHasTask(loginUserId, taskId)) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_UPDATE_TASK));
		}

		// 要添加的用户不存在于任务所在圈子
		if (!taskService.userHasTask(userId, taskId)) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FIND_USER_NULL));
		}

		taskService.addAttention(taskId, userId);
			//修改执行者的日志
		logService.insertTaskLog(taskId, LogService.HANDLE.ADD , LogService.TaskHandleField.TASK_USER_ATTENTION,loginUserId,taskService.getUserNameByTask(taskId,loginUserId),taskService.getUserNameByTask(taskId,userId)) ;

		return taskService.getAttention(taskId);
	}

	/**
	 * 修改任务关注者
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/tasks/{taskId}/users", method = RequestMethod.PUT)
	public List<UserEntity> updateAttentions(@PathVariable("taskId") Long taskId,
											 @RequestParam(value = "userId", required = true) String userIdList,
											 @RequestAttribute("userFlag") String userFlag,
											 @RequestAttribute("loginUserId") Long loginUserId)
			throws Exception {

		// 任务不属于用户
		if (!taskService.userHasTask(loginUserId, taskId)) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_UPDATE_TASK));
		}

		//转换userid
		ArrayList<Long> userIds = new ArrayList<Long>();
		String[] ids = userIdList.split(",");
		for (String string : ids) {
			try {
				userIds.add(Long.parseLong(string));
			} catch (Exception e) {
			}
		}
		// 清空关注者
		//taskService.removeAllAttention(taskId,loginUserId);
		taskService.updateAttentions(taskId,userIds,loginUserId) ;
		//发送任务的同步
		websocketService.sendTask(loginUserId,taskService.getCirclesByTask(taskId,loginUserId).getCircleId(),taskId, WebsocketService.TaskPropertise.ATTENTION, WebsocketService.Control.ADD,userIds,userFlag);
		return taskService.getAttention(taskId);
	}

	/**
	 * 删除任务的用户关注
	 *
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/tasks/{taskId}/users/{userId}", method = RequestMethod.DELETE)
	public List<UserEntity> deleteUser(@PathVariable("taskId") Long taskId, @PathVariable("userId") Long userId,
									   @RequestAttribute("loginUserId") Long loginUserId,
									   @RequestAttribute("userFlag") String userFlag) throws Exception {
		// 任务不属于用户
		if (!taskService.userHasTask(loginUserId, taskId)) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_UPDATE_TASK));
		}
		taskService.removeAttention(taskId, userId,loginUserId);
		//发送任务的同步
		websocketService.sendTask(loginUserId,taskService.getCirclesByTask(taskId,loginUserId).getCircleId(),taskId, WebsocketService.TaskPropertise.ATTENTION, WebsocketService.Control.DELETE,userId,userFlag);
		return taskService.getAttention(taskId);
	}

	/**
	 * 新增文件并返回URL 地址
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/tasks/{taskId}/file", method = RequestMethod.POST)
	public JSONObject addFile(@PathVariable("taskId") Long taskId, String fileName, HttpServletRequest request, Long fileSize) throws Exception {
		Long userId = getLoginUserId(request);
		// 任务不属于用户
		if (!taskService.userHasTask(userId, taskId)) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_UPDATE_TASK));
		}

		//文件名的校验
		if(StringUtils.isNullOrEmpty(fileName) || fileName.length() > 100 ) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FILE_NAME_ERROR));
		}
		return fileService.getTaskPostUrl(userId, taskId,fileName,fileSize);
	}

	/**
	 * 获取任务分享,的签名
	 * @param taskId
	 * @param loginUserId
	 * @return
	 * @throws GlobalErrorInfoException
	 */
	@RequestMapping(value = "/task/{taskId}/action/{type}", method = RequestMethod.GET)
	public JSONObject getShareSign(@PathVariable("taskId") Long taskId,@RequestAttribute("loginUserId") Long loginUserId,@PathVariable("type") String type,@RequestParam(required = true) String encryptedData, @RequestParam(required = true) String iv) throws GlobalErrorInfoException {

		if (!ShareInvite.CONTROL_SHARE_TASK.equals(type)) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.CIRCLE_ERROR_TYPE));
		}

		//获取群ID
		String groupId = wxService.getGroupId(encryptedData, iv, loginUserId);
		if(!StringUtils.isNullOrEmpty(groupId)) {
			wxGroupService.saveUserGroup(loginUserId,groupId);
		}

		CircleEntity circle = circleService.selectCircleByTask(taskId, loginUserId);
		//不是圈子中的成员
		if (circle == null ) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_VIEW_CIRCLE));
		}

		//没有权限分享圈子
		if (ShareInvite.CONTROL_SHARE_TASK.equals(type) && !circle.getUserCanMemberShare()) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBID_SHARE));
		}

		ShareInvite cs = new ShareInvite();
		cs.setControlId(taskId);
		cs.setControlUser(loginUserId);
		if (ShareInvite.CONTROL_SHARE_TASK.equals(type)) {
			cs.setControlType(ShareInvite.CONTROL_SHARE_TASK);
		}

		cs.setCreateTime(new Date());
		JSONObject jSing = new JSONObject();
		jSing.put("sign", AESUtils.encrypt(JSONObject.toJSONString(cs), CIRCLE_SIGN_KEY));
		jSing.put("expire", CIRCLE_SIGN_TIME);
		return jSing;
	}

	/**
	 * 处理任务分享,邀请
	 * @param taskId
	 * @param loginUserId
	 * @return
	 * @throws GlobalErrorInfoException
	 */
	@RequestMapping(value = "/task/{taskId}/sign", method = RequestMethod.POST)
	public JSONObject controlShareSign(@PathVariable("taskId") Long taskId,@RequestAttribute("loginUserId") Long loginUserId,@RequestParam(value = "sign", required = true) String sign) throws GlobalErrorInfoException, IOException {

		ShareInvite json = JSONObject.parseObject(AESUtils.decrypt(sign, CIRCLE_SIGN_KEY),ShareInvite.class) ;
		if(json == null || !taskId.equals(json.getControlId())) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.CIRCLE_ERROR_TYPE));
		}

		JSONObject rj = new JSONObject() ;
		TaskEntity task ;
		CircleEntity circle = circleService.selectCircleByTask(json.getControlId(), json.getControlUser());

		//是分享任务 并且有权限分享圈子则 返回圈子信息
		if (ShareInvite.CONTROL_SHARE_TASK.equals(json.getControlType()) && circle.getUserCanMemberShare()) {
			task = taskService.selectTaskById(taskId);
		}else {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_VIEW_TASK));
		}

		//任务已不存在
		if(task == null || task.getIsdelete() == 1) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.TASK_DELETED));
		}

		rj.put("type",json.getControlType()) ;
		rj.put("write",taskService.userHasTask(loginUserId, taskId)) ;
		rj.put("data",task) ;
		//}
		return rj;
	}

	/**
	 * 添加标签任务
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/task/{taskId}/label/{labelId}", method = RequestMethod.POST)
	public void addLabelToTask(@PathVariable("taskId") Long taskId,
							   @PathVariable("labelId") Long labelId,
							   LabelTaskEntity labelTaskEntity,
							   @RequestAttribute("loginUserId") Long loginUserId,
							   @RequestAttribute("userFlag") String userFlag) throws Exception{

		// 任务不属于用户
		if (!taskService.userHasTask(loginUserId, taskId)) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_UPDATE_TASK));
		}

		CircleEntity circleEntity = circleService.selectCircleByTask(taskId, loginUserId);;

		//圈子中是否存在此标签
		if (!labelService.existCircleLabel(circleEntity.getCircleId(),labelId)) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.CIRCLE_NOT_EXIST_LABEL));
		}

		//任务中是否存在此标签
		if (labelService.existTaskLabel(taskId,labelId)) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.TASK_EXIST_LABEL));
		}
		labelService.insertToTask(labelTaskEntity,circleEntity.getCircleId(),loginUserId,userFlag) ;
	}

	/**
	 * 删除标签任务
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/task/{taskId}/label/{labelId}", method = RequestMethod.DELETE)
	public void deleteTaskLabel(@PathVariable("taskId") Long taskId,
								@PathVariable("labelId") Long labelId,
								LabelTaskEntity labelTaskEntity,
								@RequestAttribute("loginUserId") Long loginUserId,
								@RequestAttribute("userFlag") String userFlag) throws Exception{

		// 任务不属于用户
		if (!taskService.userHasTask(loginUserId, taskId)) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_UPDATE_TASK));
		}

		CircleEntity circleEntity = circleService.selectCircleByTask(taskId, loginUserId);;

		//圈子中是否存在此标签
		if (!labelService.existCircleLabel(circleEntity.getCircleId(),labelId)) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.CIRCLE_NOT_EXIST_LABEL));
		}

		//圈子中是否存在此标签
		if (!labelService.existTaskLabel(taskId,labelId)) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.TASK_NOT_EXIST_LABEL));
		}

		labelService.deleteTaskLabel(taskId,labelId,circleEntity.getCircleId(),loginUserId,userFlag) ;
	}

}